home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17632 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news.cais.com!news
  2. From: Lally Singh <lsingh@ids2.idsonline.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: HELP Borland C++ 5.0 pointer problem
  5. Date: Tue, 16 Apr 1996 16:58:04 -0400
  6. Organization: Capital Area Internet Service info@cais.com 703-448-4470
  7. Message-ID: <317409DC.59B@ids2.idsonline.com>
  8. References: <4klke8$7mb@dub-news-svc-2.compuserve.com> <316e9fdb.457757@10.0.2.1>
  9. NNTP-Posting-Host: ip190.idsonline.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (Win95; I)
  14.  
  15. Adam Gensler wrote:
  16. > That won't work because when you leave the function the memeory reserved for 
  17. > buffer[20] is marked as free.                            ^^^^- almost, actually, it's created in the stack.
  18. > >Could you please tell me why the function below compiles and operates
  19. > >correctly under win16 but not win32 ?
  20.  
  21. > >  char* test_function(char *in_data) {
  22. > >
  23. > >       char buffer[20];
  24. > >       strcpy(buffer, in_data);   // copy in_data to buffer
  25. > >       in_data = buffer;   // set pointer to buffer
  26. > >
  27. > >       return(in_data);
  28. > >
  29. > >  }  // end test_function function
  30.  
  31. Mr. Gensler is correct in that the buffer is not available after the function
  32. ends, but it is not marked free, it was never in the heap, rather in the stack.
  33. When the function returns, the stack is cleaned up and then the next time something
  34. is pushed or popped, then that data is overwritten.
  35. If under Win32 you get garbage, then that is what's happening.  If you get something
  36. like a general protection fault, then the fault is from an attempt to access a
  37. memory address beyond the range of the stack (meaning that the stack pointer has been
  38. moved back before the place where it was when the buffer was allocated) and thus
  39. you're trying to get an invalid address, which Win32 I know doesn't like too much.
  40.  
  41. To fix it, you have to do something like this:
  42.  
  43. char * testfunction( char * inData)
  44. {
  45.     char * buffer = new[] char[20]; // allocates on the heap, remember to delete[] it!
  46.     strcpy( buffer, inData );       // copy the string
  47.     return buffer;                  // return the new buffer
  48. };
  49.